package cn.xscrum.vtsp.controller;

import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import cn.xscrum.common.annotation.Log;
import cn.xscrum.common.enums.BusinessType;
import cn.xscrum.vtsp.domain.VtspFilelogs;
import cn.xscrum.vtsp.service.IVtspFilelogsService;
import cn.xscrum.common.core.controller.BaseController;
import cn.xscrum.common.core.domain.AjaxResult;
import cn.xscrum.common.utils.poi.ExcelUtil;
import cn.xscrum.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 文件资料Controller
 *
 * @author zhangh
 * @date 2021-10-01
 */
@Controller
@RequestMapping("/vtsp/filelogs")
public class VtspFilelogsController extends BaseController
{
    private String prefix = "vtsp/filelogs";

    @Autowired
    private IVtspFilelogsService vtspFilelogsService;

    @RequiresPermissions("vtsp:filelogs:view")
    @GetMapping()
    public String filelogs() {
        return prefix + "/filelogs";
    }

    /**
     * 查询文件资料列表
     */
    @RequiresPermissions("vtsp:filelogs:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(VtspFilelogs vtspFilelogs)
    {
        startPage();
        List<VtspFilelogs> list = vtspFilelogsService.selectVtspFilelogsList(vtspFilelogs);
        return getDataTable(list);
    }
    /**
     * 查看文件详情
     *
     * @param fileLogid 文件资料唯一表示
     * @param mmap ModelMap对象
     * @return 文件资料详情列表
     */
    @GetMapping("/detail/{fileLogid}")
    public String detail(@PathVariable("fileLogid") Long fileLogid, ModelMap mmap)
    {
        //根据fileLogid查询资料信息
        VtspFilelogs vtspFilelogs = vtspFilelogsService.selectVtspFilelogsById(fileLogid);
        //展示详情页面的数据/
        mmap.put("vtspFilelogs", vtspFilelogs);
        return prefix + "/detail";
    }



    /**
     * 导出文件资料列表
     */
    @RequiresPermissions("vtsp:filelogs:export")
    @Log(title = "文件资料", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(VtspFilelogs vtspFilelogs)
    {
        List<VtspFilelogs> list = vtspFilelogsService.selectVtspFilelogsList(vtspFilelogs);
        ExcelUtil<VtspFilelogs> util = new ExcelUtil<VtspFilelogs>(VtspFilelogs.class);
        return util.exportExcel(list, "filelogs");
    }


    /**
     * 新增文件资料
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存文件资料
     */
    @RequiresPermissions("vtsp:filelogs:add")
    @Log(title = "文件资料", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(VtspFilelogs vtspFilelogs)
    {
        return toAjax(vtspFilelogsService.insertVtspFilelogs(vtspFilelogs));
    }

    /**
     * 修改文件资料
     */
    @GetMapping("/edit/{fileLogid}")
    public String edit(@PathVariable("fileLogid") Long fileLogid, ModelMap mmap)
    {
        VtspFilelogs vtspFilelogs = vtspFilelogsService.selectVtspFilelogsById(fileLogid);
        mmap.put("vtspFilelogs", vtspFilelogs);
        return prefix + "/edit";
    }

    /**
     * 修改保存文件资料
     */
    @RequiresPermissions("vtsp:filelogs:edit")
    @Log(title = "文件资料", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(VtspFilelogs vtspFilelogs)
    {
        System.out.println("请求了此方法");
        System.out.println("前端传来的参数 --------------" + vtspFilelogs);
        return toAjax(vtspFilelogsService.updateVtspFilelogs(vtspFilelogs));
    }

    /**
     * 删除文件资料
     */
    @RequiresPermissions("vtsp:filelogs:remove")
    @Log(title = "文件资料", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(vtspFilelogsService.deleteVtspFilelogsByIds(ids));
    }

    //新增（文件上传下载）
    @RequestMapping(value = "/uploadFile.do", produces = "text/html;charset=utf-8")
    public @ResponseBody
    void importPicFile1(
            @RequestParam MultipartFile file1, HttpServletRequest request) {

        Map<String, Object> map = new HashMap<String, Object>();
        if (file1.isEmpty()) {
            map.put("result", "error");
            map.put("msg", "上传文件不能为空");
        } else {
            String originalFilename = file1.getOriginalFilename();
            String fileBaseName = FilenameUtils.getBaseName(originalFilename);
            Date now = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String floderName = fileBaseName + "_" + df.format(now);
            try {
                //创建要上传的路径
                File fdir = new File("D:/");
                if (!fdir.exists()) {
                    fdir.mkdirs();
                }
                //文件上传到路径下
                FileUtils.copyInputStreamToFile(file1.getInputStream(), new File(fdir, originalFilename));
                //coding
                map.put("result", "success");

            } catch (Exception e) {
                map.put("result", "error");
                map.put("msg", e.getMessage());

            }
        }
    }
    /**
     * 文件下载
     * @throws IOException
     */
    @RequestMapping(value="/download",method=RequestMethod.GET)
    public void download(@RequestParam(value="filename")String filename,
                         HttpServletRequest request,
                         HttpServletResponse response) throws IOException {
        //模拟文件，myfile.txt为需要下载的文件
        String path = "D:\\file"+"\\"+filename;
        //获取输入流
        InputStream bis = new BufferedInputStream(new FileInputStream(new File(path)));
        //转码，免得文件名中文乱码
        filename = URLEncoder.encode(filename,"UTF-8");
        //设置文件下载头
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);
        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
        response.setContentType("multipart/form-data");
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        int len = 0;
        while((len = bis.read()) != -1){
            out.write(len);
            out.flush();
        }
        out.close();
    }
}

